(function() {
$(document).ready(function() { 	
	
	var i = 0;
	
	/* Table Article initialisation */
	var postTable = $('#posttableau').dataTable( {
		"bProcessing": true,
        "sAjaxSource": BASE_URL+"admin/getposts",
        "aoColumns": [
            { "mData": "id" },
			{ "mData": "titre" },
			{ "mData": "description" },
			{ "mData": "date" },
			{ "mData": "photo" },
			{ "mData": "langueid" },
			{ "mData": "langue" }
        ],
		"aoColumnDefs": [
                        { "bVisible": false,  "aTargets": [ 0 ]},
						{ "sWidth": '50%',  "aTargets": [ 1 ]},
                        { "bVisible": false,  "aTargets": [ 2 ]},
						{ "sWidth": '30%',  "aTargets": [ 3 ]},
						{ "bVisible": false,  "aTargets": [ 4 ]},
						{ "bVisible": false,  "aTargets": [ 5 ]},
						{ "sWidth": '20%',  "aTargets": [ 6 ]}
                    ],
		"oLanguage": {
					"sUrl": BASE_URL+"file/datatable.txt"
			  },
		"sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
		"sWrapper": "dataTables_wrapper form-inline",
		"sPaginationType": "bootstrap"
	} );
	
	
	$("#posttableau tbody tr").live('click', function( e ) {
		
		postTable.$('tr.row_selected').removeClass('row_selected');
        $(this).addClass('row_selected');
        
		//On reset le form
		resetform($('#formpost'),$('#errorPost'),"#127874");
		
		//On préremplie le formulaire
		var data = postTable.fnGetData( this );
		$('#idpost').val(data.id);
		$('#titrepost').val(data.titre);
		$('#descriptionpost').val(data.description);
		$('#langue').val(data.langueid);
		//TODO  Date ?? Quoi faire
		
		$('#photo').val(data.photo);
		
		$('#dialogpost').width('800px');
		$('#dialogpost').css('margin-left','-400px');
		$('#photocontainer').css('display','block');
		var img = "<img src='"+BASE_URL+$('#photo').val()+"?i="+i+"'/>";
		i=i+1;
		$("#photocontainer").html(img);
		$("#photocontainer").show();
		
		$('#addPostContainer').hide();
		$('#editPostContainer').show();
		
		$('#dialogpost').modal('show');
    });
	
	$('#addCanevasPost').live('click',function(e)
	{
		e.preventDefault();
		$('#addPostContainer').show();
		$('#editPostContainer').hide();
		
		$('#dialogpost').width('auto');
		$('#dialogpost').css('margin-left','-250px');
		$("#photocontainer").hide();
		
		resetform($('#formpost'),$('#error POST'),"#127874");
		
		$('#dialogpost').modal('show');
	});
	
	$('#addPost').live('click',function(e)
	{
		e.preventDefault();
		$('#actionpost').val('add');
		renamePhoto("photos","actualite",$('#titrepost'), $('#extension'),$('#photo'));
		$('#successPost').html('Votre Actualité a été ajoutée');
		$("#formpost").submit();
	});
	
	$('#cancelAddPost').live('click',function(e)
	{
		e.preventDefault();
		$('#dialogpost').modal('hide');
	});
	
	$('#editPost').live('click',function(e)
	{
		e.preventDefault();
		$('#actionpost').val('edit');
		if($('#nomphoto').val() !=  '')
		{
			renamePhoto("photos","actualite",$('#titrepost'), $('#extension'),$('#photo'));
		}
		$('#successPost').html('Votre Actualité a été modifiée');
		$("#formpost").submit();
	});
	
	$('#deletePost').live('click',function(e)
	{
		e.preventDefault();
		
		//On cache la premiere DialogBox
		$('#dialogpost').modal('hide');
		
		//On demande Confirmation
		$('#confirmdeletepost').modal('show');
	});
	
	$('#ValiddeletePost').live('click',function(e)
	{
		e.preventDefault();
		$('#actionpost').val('delete');
		$('#successPost').html('Votre Post a été supprimé');
		$("#formpost").submit();
		$('#confirmdeletepost').modal('hide');
	});
	
	$('#CanceldeletePost').live('click',function(e)
	{
		e.preventDefault();
		$('#confirmdeletepost').modal('hide');
	});
	
	$("#formpost").live('submit',function(e) {
		e.preventDefault(); // stop the form being submit on click
			
		//On remet la couleur sur chaque des bordures input
		reInitCouleurlabel($(this), "#127874");
		
		//On réinitialise les message d'erreurs
		$('#errorPost').html("");
			
		var formulaire = $(this);
		//On récupère l'action du form
		var url = $(this).attr("action");    
					
		$.ajax({
				type: "POST",
				url: url,
				data: $(this).serialize(), //On sérialize les datas du form
				beforeSend: function () {
					$("#loadpost").show();
				},
				success: function(data, textStatus, jqXHR) {
					
				$("#loadpost").hide();
						
				//Si la validation passe
				if(data == "true")
				{
					//On cache le form
					$('#dialogpost').modal('hide');
					
					$("#file_upload").uploadify("settings", 'formData', {'titrephoto':$('#photo').val()});	
					//On upload le file
					$('#file_upload').uploadify('upload');
					
					//On reload la table actuelle
					postTable.fnReloadAjax();
						
					//On Reset le Form
					resetform(formulaire,$('#errorPost'),"#127874");
					
					//On affiche un message de succès
					$('#successPost').show();
					setTimeout(function() {
						$('#successPost').hide();
					}, 5000);
				}
				//Si la validation échoue
				else
				{
					$('#errorPost').show();
					res = $.parseJSON(data);
					for (var id in res) {
						$('#'+id).prev().css('color','red');
						for(var id2 in res[id]) {
							if($('#errorPost').text() == "")
							{
								//On affiche un message d'erreur
								$('#errorPost').css('display','block');
								$('#errorPost').append(res[id][id2]);
							}
						}
					}
				}
				}
		});
	});
	
	$('#file_upload').uploadify({
		'method'   : 'post',
        'swf'      : BASE_URL+'flash/uploadify.swf',
		'fileSizeLimit' : '0',
        'uploader' : BASE_URL +'admin/upload',
		'onUploadError' : function(file, errorCode, errorMsg, errorString) {
				alert('The file ' + file.name + ' a eu un problème : ' + errorString +'"\n"'+errorMsg);
		} ,
        'onUploadComplete' : function(file) {
				$('#loadupload').hide();
			},
		'onUploadSuccess' : function(file, data, response) {
				console.log(data);
				//alert(response);
			},
		'onSelect' : function(file) {
				checkExtensionPhoto(file.name, $('#extension'),$('#errorPost'), $('#nomphoto'));
		    }, 
		'onInit'   : function(instance) {
			
				$('#file_upload').css('width','100%');
				$('#file_upload').prepend('<div class="mylabel"><span>Photo :</span></div><input id="nomphoto" name="nomphoto" type="text" class="myinput" value=""/>');
				$('#file_upload').append('<div class="clearfix"></div>');
				
				$('#file_upload .swfupload').css('margin-left',-$('#file_upload-button').width());
				
				$('#file_upload-queue').css('display','none');
			},
		 'onUploadStart' : function(file) {
				$('#loadupload').show();
			},
			'buttonClass':'mybutton',
			'buttonText' : 'parcourir...',
			'queueID'  : 'photo_queue',
			'multi':false,
			'auto': false
	});
	
}); 
})( jQuery );